package com;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class Main {
    private static KeyGenerator keyGenerator;

    static {
        try {
            keyGenerator = KeyGenerator.getInstance("AES");
            keyGenerator.init(128);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }


    // 获取密钥字节数组
    private static byte[] keyBytes = keyGenerator.generateKey().getEncoded();

    public static void main(String[] args) throws Exception {
        // 生成AES密钥

        // 加密字符串
        String originalString = "这是一个需要加密的字符串";
        byte[] encryptedBytes = encrypt(originalString, keyBytes);
        String encryptedString = Base64.getUrlEncoder().encodeToString(encryptedBytes);
        System.out.println("加密后的字符串: " + encryptedString);

        // 解密字符串
        byte[] decryptedBytes = decrypt(encryptedString, keyBytes);
        String decryptedString = new String(decryptedBytes);
        System.out.println("解密后的字符串: " + decryptedString);
    }

    public static byte[] encrypt(String str, byte[] keyBytes) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        return cipher.doFinal(str.getBytes());
    }

    public static byte[] decrypt(String str, byte[] keyBytes) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        return cipher.doFinal(Base64.getUrlDecoder().decode(str));
    }
}
